import { Card, Button } from 'flowbite-react'
import { FaBook, FaDownload, FaUpload } from 'react-icons/fa'
import { storage } from '@/services/storage'

export default function DeckSelection({ decks, dailyStats, onStartStudy, onDataChange }) {
  const handleExportDeck = (deck) => {
    const cards = storage.getCardsByDeck(deck.id)
    const exportData = {
      deck,
      cards
    }
    
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${deck.name}-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const handleImportDeck = async (event) => {
    const file = event.target.files[0]
    if (file) {
      try {
        const text = await file.text()
        const importData = JSON.parse(text)
        
        // 生成新的 ID 避免冲突
        const newDeck = {
          ...importData.deck,
          id: Date.now().toString(),
          created: new Date(),
          modified: new Date()
        }
        
        // 保存卡片组
        storage.saveDeck(newDeck)
        
        // 保存所有卡片并更新关联
        importData.cards.forEach(card => {
          const newCard = {
            ...card,
            id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
            deck: newDeck.id,
            created: new Date(),
            modified: new Date()
          }
          storage.saveCard(newCard)
        })
        
        // 通知父组件数据已更新
        onDataChange?.()
      } catch (error) {
        console.error('Import error:', error)
        alert('导入失败：文件格式不正确')
      }
    }
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold text-gray-900">选择要学习的卡片组</h1>
        <div className="text-right">
          <div className="text-3xl font-bold text-blue-600">{dailyStats.totalDue}</div>
          <div className="text-sm text-gray-500">今日待复习</div>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2  lg:grid-cols-3  gap-6">
        {decks.map(deck => {
          const deckStat = dailyStats.deckStats.find(s => s.deckId === deck.id)
          return (
            <Card key={deck.id} className="hover:shadow-lg transition-shadow">
              <div className="flex justify-between items-start mb-4">
                <div>
                  <h2 className="text-xl font-bold text-gray-900 mb-2">{deck.name}</h2>
                  <p className="text-gray-600">{deck.description}</p>
                </div>
                <div className="flex gap-2">
                  <Button 
                    size="xs" 
                    color="gray"
                    onClick={() => handleExportDeck(deck)}
                  >
                    <FaDownload className="mr-1" />
                    导出
                  </Button>
                </div>
              </div>
              <div className="flex items-center justify-between gap-4 mb-4 text-sm text-gray-500">
                <div className="flex items-center">
                  <FaBook className="mr-2" />
                  待复习：{deckStat?.dueCount || 0} 张
                </div>
                <div className="text-gray-400">
                  总计：{deckStat?.totalCards || 0} 张
                </div>
              </div>
              <div className="flex gap-2">
                <Button 
                  color="blue" 
                  onClick={() => onStartStudy(deck.id)}
                  disabled={!deckStat?.dueCount}
                  className="flex-1"
                >
                  {deckStat?.dueCount > 0 ? '开始学习' : '无可复习'}
                </Button>
                <Button 
                  color="gray"
                  onClick={() => handleExportDeck(deck)}
                  className="flex-none"
                >
                  <FaDownload className="mr-1" />
                  导出
                </Button>
                <label className="flex-none">
                  <input
                    type="file"
                    accept=".json"
                    onChange={handleImportDeck}
                    className="hidden"
                  />
                  <Button as="span" color="gray">
                    <FaUpload className="mr-1" />
                    导入
                  </Button>
                </label>
              </div>
            </Card>
          )
        })}
      </div>
    </div>
  )
}